package com.lebang.component;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.common.utils.IOUtils;
import com.aliyun.oss.model.*;
import com.lebang.configuration.OSSConstantConfig;
import com.lebang.domain.TaskRouseDetail;
import com.lebangweb.common.TextUtil;
import com.lebangweb.common.UUIDUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Formatter;
import java.util.List;

/**
 * @author Eliohn on 2019/7/24.
 * @version 1.0
 */
@Component
public class AliOSSComment {
    @Autowired
    private OSSConstantConfig ossConstantConfig;
    private static final String HOST_NANE = "http://imgxy.lbappstore.com";
    private static final String NEW_HOTST_NAME="http://xyimg.hotbuybuy.com";
    private static final Logger logger = LoggerFactory.getLogger(AliOSSComment.class);
    @Value("${alioss.pref-xytaskapk}")
    private String prefXyTaskApk;
    public void uploadData(String yourObjectName, String content) {
        try {
            // 创建文件元信息。
            ObjectMetadata meta = new ObjectMetadata();
            String md5 = BinaryUtil.encodeMD5(content.getBytes());
            // 设置自定义元信息property值为property-value。建议使用Base64编码。
            meta.addUserMetadata("md5", md5);
            OSS ossclient = new OSSClientBuilder().build(ossConstantConfig.getEndPoint(), ossConstantConfig.getKeyId(), ossConstantConfig.getKeySecret());
            ossclient.putObject(ossConstantConfig.getBucketname(), yourObjectName, new ByteArrayInputStream(content.getBytes()), meta);
            ossclient.shutdown();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }

    public Boolean uploadImg(String yourObjectName, InputStream inputStream) {
        try {
            // 创建文件元信息。
            ObjectMetadata meta = new ObjectMetadata();
//            String md5 = BinaryUtil.encodeMD5(content.getBytes());
            // 设置自定义元信息property值为property-value。建议使用Base64编码。
//            meta.addUserMetadata("md5", md5);
            OSS ossclient = new OSSClientBuilder().build(ossConstantConfig.getEndPoint(), ossConstantConfig.getKeyId(), ossConstantConfig.getKeySecret());
            PutObjectResult putObjectResult = ossclient.putObject(ossConstantConfig.getBucketname(), yourObjectName, inputStream, meta);
            // 读取上传回调返回的消息内容。
//            byte[] buffer = new byte[1024];
//            putObjectResult.getResponse().getContent().read(buffer);
//            // 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
//            putObjectResult.getResponse().getContent().close();
//
//            System.out.println(new String(buffer));
            ossclient.shutdown();

            return true;
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }

    public Boolean objectExist(String yourObjectName) {
        boolean b = false;
        try {
            OSS ossclient = new OSSClientBuilder().build(ossConstantConfig.getEndPoint(), ossConstantConfig.getKeyId(), ossConstantConfig.getKeySecret());
            b = ossclient.doesObjectExist(ossConstantConfig.getBucketname(), yourObjectName);
            ossclient.shutdown();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return b;
    }

    public String getObject(String yourObjectName) {
        StringBuilder dataContent = new StringBuilder();
        OSS ossclient = new OSSClientBuilder().build(ossConstantConfig.getEndPoint(), ossConstantConfig.getKeyId(), ossConstantConfig.getKeySecret());
        OSSObject ossObject = null;
        try {

            ossObject = ossclient.getObject(ossConstantConfig.getBucketname(), yourObjectName);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        BufferedReader reader = null;
        try {
            if (ossObject == null) {
                return "";
            }
            reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));
            while (true) {
                String line = null;
                line = reader.readLine();
                if (line == null) {
                    break;
                } else {
                    dataContent.append(line);
                }
            }


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            ossclient.shutdown();
        }
        return dataContent.toString();
    }


    /**
     * 图片加水印
     *
     * @param sourceImage 源图
     */
    public void imgWatermark(String sourceImage) {
        try {
            OSS ossClient = new OSSClientBuilder().build(ossConstantConfig.getEndPoint(), ossConstantConfig.getKeyId(), ossConstantConfig.getKeySecret());
            // 图片处理持久化 : 缩放
            StringBuilder sbStyle = new StringBuilder();
            Formatter styleFormatter = new Formatter(sbStyle);
            String styleType = "image/info";
            // 获取图片信息
            GetObjectRequest getrequest = new GetObjectRequest(ossConstantConfig.getBucketname(), sourceImage);
            getrequest.setProcess(styleType);
            OSSObject objectMetadata = ossClient.getObject(getrequest);
            InputStream st = objectMetadata.getObjectContent();
            String text = IOUtils.readStreamAsString(st, "utf-8");

            JSONObject jsonObject = JSONObject.parseObject(text);
//            jsonObject.getJSONObject("ImageHeight").getIntValue("value");
            int imgWidth = jsonObject.getJSONObject("ImageWidth").getIntValue("value");
//            jsonObject.getJSONObject("ResolutionUnit").getIntValue("value");

            int size = imgWidth / 3;

            // 图片处理持久化 : 水印
            sbStyle.delete(0, sbStyle.length());
            styleType = String.format("image/watermark,type_d3F5LXplbmhlaQ,size_%d,text_5Zu-5L6L,color_FF0000,t_90,g_center,voffset_0,rotate_315", size);

            styleFormatter.format("%s|sys/saveas,o_%s,b_%s", styleType,
                    BinaryUtil.toBase64String(sourceImage.getBytes()),
                    BinaryUtil.toBase64String(ossConstantConfig.getBucketname().getBytes()));

            ProcessObjectRequest request = new ProcessObjectRequest(ossConstantConfig.getBucketname(), sourceImage, sbStyle.toString());
            GenericResult processResult = ossClient.processObject(request);
            String json = null;

            json = IOUtils.readStreamAsString(processResult.getResponse().getContent(), "UTF-8");

            processResult.getResponse().getContent().close();


            ossClient.shutdown();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    public String uploadByUrl(String url,Long id) {
        try {
            DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMdd");
            // 上传网络流。
            OSS ossclient = new OSSClientBuilder().build(ossConstantConfig.getEndPoint(), ossConstantConfig.getKeyId(), ossConstantConfig.getKeySecret());
            String objName = prefXyTaskApk+"/"+id+"/"+LocalDate.now().format(df) + "/" + UUIDUtil.L() + ".apk";
            InputStream inputStream = null;
            try {
                inputStream = new URL(url).openStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            ossclient.putObject(ossConstantConfig.getBucketname(), objName, inputStream);
            ossclient.shutdown();
            return NEW_HOTST_NAME + "/"+objName;
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void deleteObject(String objName){

        OSS ossclient = new OSSClientBuilder().build(ossConstantConfig.getEndPoint(), ossConstantConfig.getKeyId(), ossConstantConfig.getKeySecret());

        ossclient.deleteObject(ossConstantConfig.getBucketname(),objName);
        // 关闭OSSClient。
        ossclient.shutdown();
    }
    public void deleteApkObject(List<TaskRouseDetail> list){

        OSS ossclient = new OSSClientBuilder().build(ossConstantConfig.getEndPoint(), ossConstantConfig.getKeyId(), ossConstantConfig.getKeySecret());
        for (TaskRouseDetail model:list){
            try {
                if(!TextUtil.isEmpty(model.getDownUrl())){
                    ossclient.deleteObject(ossConstantConfig.getBucketname(),model.getDownUrl().replace(NEW_HOTST_NAME + "/",""));
                   // System.out.println("删除成功"+model.getDownUrl());
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        // 关闭OSSClient。
        ossclient.shutdown();
    }
}
